<?php

namespace app\api\controller;

use app\api\validate\AddressValidate;
use app\common\controller\UserBase;

class Address extends UserBase
{
    
    public function add()
    {
        $data = (new AddressValidate)->doCheck('add');
        if ($data) {
            $data['user_id'] = $this->uid;
            if (!empty($data['id'])) {
                $address = \app\common\model\Address::update($data);
            } else {
                $address = \app\common\model\Address::create($data);
            }
            $this->success();
        }
    }
    
    public function edit()
    {
        $data = (new AddressValidate())->doCheck('edit');
        $address = \app\common\model\Address::update($data);
        $this->success();
    }
    
    public function del()
    {
        \app\common\model\Address::where("id",input('id/d'))->where('user_id',$this->uid)->delete();
        $this->success();
    }
    
    public function getList()
    {
        $where = [];
        $type = input("type");
        if ($type == 'fa') $where[] = ['type',"=",'fa'];
        if ($type == 'shou') $where[] = ['type',"=",'shou'];
        $list = \app\common\model\Address::where("user_id",$this->uid)
            ->where($where)
            ->order('id desc')
            ->select();
        $select = \app\common\model\Address::where("user_id",$this->uid)
            ->where($where)->where('is_default',1)
            ->order('id desc')
            ->find();
        
        $this->success([
            "list" => $list,
            "id" => $select ? $select->id : 0
        ]);
    }
    
    public function setDefault()
    {
        $data = input();
        if (!isset($data['type'])) {
            $this->error('参数错误');
        }
        \app\common\model\Address::where("user_id",$this->uid)
            ->where('type',$data['type'])
            ->update(['is_default'=>-1]);
        \app\common\model\Address::where("id",$data['id'])
            ->where('type',$data['type'])
            ->where('user_id',$this->uid)
            ->update(['is_default'=>1]);
        $this->success();
    }
    
    public function getDefault()
    {
        $this->success([
            "shou" => \app\common\model\Address::where("user_id",$this->uid)
            ->where('is_default',1)->where('type','shou')->find(),
            "fa" => \app\common\model\Address::where("user_id",$this->uid)
            ->where('is_default',1)->where('type','fa')->find()
        ]);
    }
}